/* eslint-disable no-constant-condition */
import React, { useState } from 'react'
import classnames from 'classnames'
import { useHistory } from 'react-router'
import { Dialog, NavBar, Search } from 'antd-mobile'
import { useDebounceFn } from 'ahooks'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import {
  getSuggests,
  addHistory,
  clearHistories,
  clearItemHistory
} from '@/store/actions/search'
import { RootState } from '@/types/store'

// 高亮函数
const hightLight = (str: string, key: string) => {
  const newStr = str.replace(new RegExp(key, 'ig'), (result) => {
    console.log(result)
    return '<span>' + result + '</span>'
  })
  return newStr
}

const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 搜索关键字内容
  const [keyword, setKeyword] = useState('')
  const getSuggest = () => {
    if (keyword.trim() === '') return
    dispatch(getSuggests(keyword))
  }
  const { run } = useDebounceFn(getSuggest, { wait: 500 })
  const onChange = (key: string) => {
    setKeyword(key)
    run()
  }
  // 获取搜索数据并且渲染
  const { suggestion, searchHistory } = useSelector(
    (state: RootState) => state.search
  )
  // 搜索历史记录
  const onSearch = (key: string) => {
    if (!key) return
    dispatch(addHistory(key))
    // 跳转页面
    history.push('/search/result?key=' + key)
  }
  // 清空搜索记录
  const onClearHistory = () => {
    // 清空历史记录
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要清空记录吗？',
      onConfirm: function () {
        dispatch(clearHistories())
      }
    })
  }
  const onClearItemHistory = (item: string) => {
    dispatch(clearItemHistory(item))
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span className="search-text" onClick={() => onSearch(keyword)}>
            搜索
          </span>
        }>
        <Search
          value={keyword}
          onChange={(str) => onChange(str)}
          placeholder="请输入关键字搜索"
        />
      </NavBar>

      <div
        className="history"
        style={{
          display: keyword ? 'none' : 'block'
        }}>
        <div className="history-header">
          <span>搜索历史</span>
          <span onClick={onClearHistory}>
            <Icon type="iconbtn_del" />
            清除全部
          </span>
        </div>
        {searchHistory.map((item, idx) => (
          <div key={idx} className="history-list">
            <span className="history-item">
              <span className="text-overflow" onClick={() => onSearch(item)}>
                {item}
              </span>
              <Icon
                type="iconbtn_essay_close"
                onClick={() => onClearItemHistory(item)}
              />
            </span>
          </div>
        ))}
      </div>

      <div className={classnames('search-result', keyword ? 'show' : '')}>
        {/* {suggestion && <div>搜索列表为空!</div>} */}
        {suggestion.map((item, index) => {
          return (
            <div className="result-item" key={index}>
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                onClick={() => onSearch(item)}
                className="result-value text-overflow"
                // 让字符串中的标签生效:dangerouslySetInnerHTML
                dangerouslySetInnerHTML={{ __html: hightLight(item, keyword) }}
              />
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default SearchPage
